using System;
using System.Collections.Generic;
using Commons.Daos.Scores;
using Commons.Events;
using Commons.Models.Definitions;
using Commons.Models.Scores;
using Commons.Models.Settings;
using Commons.Utils;

namespace Commons.Services.Scores
{
	public class HighScoreService : IHighScoreService
	{
		public IHighScoreDao HighScoreDao { protected get; set; }

		protected HighScoreSettings HighScoreSettings { get { return SettingsModel.Instance.GetSettings<HighScoreSettings>(); } }

		public List<HighScore> GetHighScores()
		{
			DateTime time = DateTimeHelper.Current();
			List<HighScore> highScores = new List<HighScore>();
			foreach (HighScoreDefinition definition in HighScoreSettings.GetDefinitions())
			{
				highScores.Add(GetHighScore(definition, time));
			}

			return highScores;
		}

		public HighScore GetHighScore(int code)
		{
			return GetHighScore(HighScoreSettings.GetDefinition(code), DateTimeHelper.Current());
		}

		protected HighScore GetHighScore(HighScoreDefinition definition, DateTime time)
		{
			HighScore highScore = HighScoreDao.Get(definition.Code);
			if (highScore == null)
			{
				highScore = new HighScore(definition, time, 0, 0, 0);
				HighScoreDao.Insert(highScore);
			}
			else if (highScore.CheckPeriod(time))
			{
				HighScoreDao.Update(highScore);
			}

			return highScore;
		}

		public void OnEvent(object sender, BasicEventArgs eventArgs)
		{
			DateTime time = DateTimeHelper.Current();
			foreach (HighScoreDefinition definition in HighScoreSettings.GetDefinitions())
			{
				if (definition.Matcher.Met(eventArgs))
				{
					int score = eventArgs.Count;
					HighScore highScore = HighScoreDao.Get(definition.Code);
					if (highScore == null)
					{
						highScore = new HighScore(definition, time, score, score, score);
						HighScoreDao.Insert(highScore);
					}
					else
					{
						highScore.Add(score, time);
						HighScoreDao.Update(highScore);
					}
				}
			}
		}
	}
}

